package net.wenku8.reader.view.rank

import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import net.wenku8.reader.api.BookApi
import net.wenku8.reader.entity.ApiResult
import net.wenku8.reader.model.book.BookPreviewInfo
import net.wenku8.reader.state.StateLogin
import net.wenku8.reader.state.StateSearch
import net.wenku8.reader.util.hasValue
import net.wenku8.reader.view.common.BaseViewModel

class SearchViewModel : BaseViewModel() {
    val key = mutableStateOf("")
    val bookList = mutableStateListOf<BookPreviewInfo>()

    fun initData(){
        key.value = StateSearch.key.value
        if (hasValue(key.value)){
            onSearch(StateSearch.type.value)
        }
    }

    fun onSearch(type: String){
        if (!StateLogin.status.value){
            showSnackbar("用户未登陆")
            return
        }
        viewModelScope.launch(Dispatchers.IO) {
            val apiResult = BookApi.searchBook(type, key.value)
            if (ApiResult.isSuccess(apiResult)){
                if (apiResult.data == null || apiResult.data!!.isEmpty()){
                    bookList.clear()
                    showSnackbar("未找到结果")
                }else{
                    bookList.clear()
                    bookList.addAll(apiResult.data?: emptyList())
                }
            }else{
                showSnackbar(apiResult.message)
            }
        }
    }

}